<template>
  <div class="group-tags">
    <div class="group-tags-item"
         v-for="(item, index) in data"
         :key="item.id"
         @click="onSelect(item)"
         :class="{selected: item.value === currValue}">
      {{item.label}}
      <i class="el-icon-close del-tag" v-if="typeof item.closeable !== 'undefined' ? item.closeable  : closeable" @click.stop="onRemove(item, index)"></i>
    </div>
    <div class="group-tags-add" @click="onAdd" v-show="!isInput">
      <i class="el-icon-plus"></i>
    </div>
    <div class="group-tags-input" v-show="isInput">
      <el-input v-model="name" ref="input" clearable size="small" @blur="onBlur"/>
    </div>
  </div>
</template>

<script>
export default {
  name: 'group-tags',
  cnName: 'group-tags',
  props: {
    data: {
      type: Array,
      default() {
        return []
      }
    },
    value: [String, Number],
    closeable: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      currValue: this.value,
      name: '',
      isInput: false
    }
  },
  methods: {
    onRemove(item, index) {
      this.$emit('remove', item, index)
    },
    onSelect(item) {
      if(this.currValue === item.value) {
        return
      }
      this.currValue = item.value
      this.$emit('input', this.currValue)
      this.$emit('select', item)
    },
    onAdd() {
      this.name = ''
      this.$refs.input.$el.focus()
      this.isInput = true
      this.$emit('add')
    },
    onBlur() {
      this.isInput = false
      this.$emit('addOk', this.name)
    }
  },
  watch: {
    value(nval) {
      this.currValue = nval
    }
  }
}
</script>

<style lang="less" scoped>
.group-tags {

  &-item {
    display: inline-block;
    cursor: pointer;
    text-align: center;
    line-height: 30px;
    margin-right: 2px;
    border-radius: 2px;
    padding: 0 20px;
    position: relative;

    .del-tag {
      position: absolute;
      width: 15px;
      height: 100%;
      right: 4px;
      top: 8px;
      display: none;
    }

    &:hover {
      color: #1890ff;
    }
    &.selected {
      color: #FFF;
      background-color: #1890ff;
      &:hover {
        .del-tag {
          display: block;
        }
      }
    }
  }

  &-add {
    display: inline-block;
    cursor: pointer;
    padding: 0 20px;
    line-height: 30px;
    border-radius: 2px;

    &:hover {
      background-color: rgba(0, 0, 0, .1);
    }
  }

  &-input {
    display: inline-block;
    width: 120px;
  }
}
</style>
